﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Linq;

namespace RSTAi.Platform.GrpcService.Common
{
    /// <summary>
    /// 缓存
    /// </summary>
    public class CacheHelper
    {
        private static readonly object cacheLock = new();
        private static readonly MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        private static readonly int ExpirationInMinutes = 60;//缓存过期时间
        private static readonly Random random = new();

        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCache(string key, object value)
        {
            lock (cacheLock)
            {
                object obj = new object();
                if (cache.TryGetValue(key, out obj))
                    cache.Remove(key);
                int rd = random.Next(5);
                cache.Set(key, value, TimeSpan.FromMinutes(ExpirationInMinutes + rd));
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T? GetCache<T>(string key)
        {
            object obj;
            lock (cacheLock)
            {
                if (cache.TryGetValue(key, out obj))
                {
                    var cachedValue = (T)cache.Get(key);
                    return cachedValue;
                }
                else
                {
                    return default;
                }
            }
        }

        /// <summary>
        /// 清除key的缓存
        /// </summary>
        /// <param name="key"></param>
        public static void ClearCache(string key)
        {
            object obj;
            lock (cacheLock)
            {
                if (cache.TryGetValue(key, out obj))
                {
                    cache.Remove(key);
                }
            }
        }


    }

    /// <summary>
    /// 管理缓存key
    /// </summary>
    public class CacheKey
    {
        public static readonly string token = "";

        /// <summary>
        /// 获取缓存key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cacheType"></param>
        /// <returns></returns>
        public static string GetCacheKey(string key, CacheType cacheType)
        {
            string cacheKey = key + cacheType.ToString();
            return cacheKey;
        }

    }

    public enum CacheType
    {
        token =1,
        product = 2,

    }







}
